package org.clxmm.security.springmvc.interceptor;

import org.clxmm.security.springmvc.model.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author clxmm
 * @Description
 * @create 2021-06-06 8:07 下午
 */
@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //读取会话信息
        Object object = request.getSession().getAttribute(UserDto.SESSION_USER_KEY);

        if (object == null) {
            writeContent(response, "fail;");
        }

        UserDto user = (UserDto) object;
        //请求的url
        String requestURI = request.getRequestURI();
        if (user.getAuthorities().contains("p1") && requestURI.contains("/r1")) {
            System.out.println("r1");
            return true;
        }
        if (user.getAuthorities().contains("p2") && requestURI.contains("/r2")) {
            System.out.println("r2");
            return true;
        }
        System.out.println("权限不足，拒绝访问");
        writeContent(response, "fail   111");

        return false;
    }


    //响应输出
    private void writeContent(HttpServletResponse response, String msg) throws IOException {
        response.setContentType("text/html;charset=utf‐8");
        PrintWriter writer = response.getWriter();
        writer.print(msg);
        writer.close();
        response.resetBuffer();
    }
}
